import random
from datetime import datetime
import time

from flask import request, jsonify, render_template, session, flash

from application.modules.rooms import rooms_blue
from application.utils.room.Room import Room
from application.utils.room.AI import AI_Room
from application.utils.common import dict_room


@rooms_blue.route('/rooms')
def rooms():
    list_req = []
    for key, room in dict_room.items():
        dict_req = {}
        dict_req["id"] = key
        dict_req['player'] = "%d / 2" % sum(room.list_player)
        dict_req['room'] = "双人" if type(room).__name__ == "Room" else "AI"
        dict_req["name"] = room.name
        list_req.append(dict_req)
    
    return jsonify(list_req)


@rooms_blue.route('/addRoom')
def add_room():
    # 新建一个普通房间
    room_name = request.args.get("name")
    room_type = int(request.args.get("type"))

    t = time.time()
    key = str(int(round(t * 1000)))
    if room_type == 1:
        dict_room[key] = Room(key, name=room_name)
    elif room_type == 2:
        dict_room[key] = AI_Room(key, name=room_name)
    return jsonify({"key": key})


@rooms_blue.route("/openRoom/<string:room_id>")
def open_room(room_id):
    room = None
    if dict_room.get(room_id):
        room = dict_room[room_id]
        if room.isFull():
            return "这个房间已经满了"
    else:
        return
    if type(room).__name__ == "room":
        return render_template('gobang.html', key=room_id)
    return render_template('gobangAI.html', key=room_id)

@rooms_blue.route("/roomlist/<string:id>")
def roomlist(id):
    # TODO 改为g.user验证
    if session['id'] == id:
        return render_template('/roomlist.html')
    else:
        flash("请登录后再进入")
        return render_template("/login.html")